package bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipInputStream;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;



@Controller
@Scope("prototype")
public class ProcessDefinitionAction extends ActionSupport{
	@Autowired
	private RepositoryService repositoryService;
	public String list(){
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		query.latestVersion();
		query.orderByProcessDefinitionName().desc();
		List<ProcessDefinition> list=query.list();
		ActionContext.getContext().getValueStack().set("list", list);
		return "list";
	}
	private File zipFile;
	
	public void setZipFile(File zipFile) {
		this.zipFile = zipFile;
	}

	public String deploy() throws IOException{
		DeploymentBuilder deploymentBuilder=repositoryService.createDeployment();
		
		deploymentBuilder.addZipInputStream(new ZipInputStream(
				new FileInputStream(zipFile)));
		
		deploymentBuilder.deploy();
		
		return "tolist";
	}
	private String id;
	public void setId(String id) {
		this.id = id;
	}
	
	public String showpng(){
		InputStream inputStream=repositoryService.getProcessDiagram(id);
		ActionContext.getContext().getValueStack().set("inputStream", inputStream);
		return "showpng";
	}
	
	
	public String delete(){
		String deltag="0";
		ProcessDefinitionQuery query=repositoryService.createProcessDefinitionQuery();
		query.processDefinitionId(id);
		ProcessDefinition processDefinition=query.singleResult();
		String deploymentId = processDefinition.getDeploymentId();
		try{
			repositoryService.deleteDeployment(deploymentId);
		}catch(Exception e){
			deltag="1";
			ActionContext.getContext().getValueStack().set("deltag", deltag);
			return "list";
		}
		return "tolist";
		
	}
}
